'use strict';
const fs = require('fs'); 

const ERROR = require('../config/defaultErrorInfo').defaultErrorInfo;
const wxFileSrc = require('../config/defaultWxFileSrc').wxFileSrc; 
const _fileSystem = require('../common/fileSystem');
const FILE_TYPE = 'json';

class Compile {
        constructor (fileName = '') {
                  fileName = fileName.replace(/\\/g,"/");
                  this.file =  {
                          path : fileName,
                          type : fileName.split(".").reverse()[0],
                          name : fileName.split("/").reverse()[0].split('.')[0] ,
                          root : fileName.replace(fileName.split("/").reverse()[0], "")
                  };
                  if ( this.file.type !== FILE_TYPE ) throw(ERROR[0]);
                  this.appConfig = JSON.parse(fs.readFileSync(this.file.path, "utf-8"));
                  if ( !this.appConfig.pages ) throw(error[1]); 

                  void(this._compileAll());
        }

        _compileAll () {
                this.appConfig.pages.forEach((pageName)=>{
                	let wxmlFilePath = this.file.root + pageName + ".wxml";
                	let jsFilePath = this.file.root + pageName + ".js";
                	let wxmlFileContent = fs.readFileSync(wxmlFilePath, "utf-8"); 
                	let httpRequestFn = this._compileRequestMethod(wxmlFileContent, wxmlFilePath);
                	if ( httpRequestFn ) { 
                		this._insertFn(jsFilePath, "onLoad", httpRequestFn);
                		console.log(`Compile httpRequest to ${pageName}.js : \t successfully`);
                	}
                });
        }

        _compileRequestMethod(wxmlFileContent, wxmlFilePath) {
        	let hasHttps = wxmlFileContent.split('[https://');
        	if ( hasHttps.length === 1 ) {
        		//console.log(hasHttps);
        		return false;
        	} else {
        		let url = hasHttps[1].split("]")[0];
        		let arrayName =  hasHttps[1].split("].")[1].split("}}")[0];
        		wxmlFileContent = wxmlFileContent.replace(`[https://${url}].`,"");
        		void(fs.writeFileSync(wxmlFilePath, wxmlFileContent));
        		let newHttpRequestFn = `\t\twx.request({
\t\t  url: 'https://${url}',  
\t\t  method : 'GET',
\t\t  data: {},
\t\t  header: {
\t\t      'Content-Type':'json'
\t\t  },
\t\t  success: (res) => {
\t\t       this.setData({${arrayName} : res.data.${arrayName}});
\t\t  }
\t\t});\n    `;
				return newHttpRequestFn;
        	}
        }

        _insertFn(jsPath, fnName, content) {
        	let jsContent = fs.readFileSync(jsPath, "utf-8");
        	let tempStr = jsContent.split(fnName+":")[1].split("},")[0];
        	let newStr = tempStr + "\n" +  content;
        	let newJsContent = jsContent.replace(tempStr, newStr);
        	void(fs.writeFileSync(jsPath, newJsContent)); 
        }
}

module.exports = { 
        Compile 
};